package com.sanji.sjmallutils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by fhm on 2016/12/13.
 */

public class SharePreferenceUtil {
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private static String spName = "SJMall_Share";

    /**
     * 构造方法
     */
    public SharePreferenceUtil(Context context) {
        sp = context.getSharedPreferences(spName, context.MODE_PRIVATE);
        editor = sp.edit();
    }

    /**
     * @param key   保存到键值对
     * @param value
     * @return
     */
    public SharePreferenceUtil put(String key, Object value) {
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value).commit();
        } else if (value instanceof String) {
            editor.putString(key, (String) value).commit();
        } else if (value instanceof Integer || value instanceof Byte) {
            editor.putInt(key, (Integer) value).commit();
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value).commit();
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value).commit();
        }
        return this;
    }

    /**
     * @param key
     * @param defValue
     * @return 返回获取到的值，当不存在的时候返回默认
     */
    public String getString(String key, String defValue) {
        return sp.getString(key, defValue);
    }

    public int getInt(String key, int defValue) {
        return sp.getInt(key, defValue);
    }

    public boolean getBoolean(String key, boolean defValue) {
        return sp.getBoolean(key, defValue);
    }

    /**
     * @return 清空所有的键值对
     */
    public SharePreferenceUtil clear() {
        editor.clear();
        return this;
    }

    /**
     * @param key
     * @return 要移除的键的名称
     */
    public SharePreferenceUtil remove(String key) {
        editor.remove(key);
        return this;
    }
}
